#include "NfcEngine.h"

#include "P2PManager.h"

#include "NfcClient.h"
#include "Log.h"

CNfcEngine::CNfcEngine()
    {
    // No implementation required
    }

CNfcEngine::~CNfcEngine()
    {
    iClients.Close();
    iEnumCleanup.Close();
    
    DELETE_LOG_INSTANCE();
    iFs.Close();
    }

CNfcEngine* CNfcEngine::NewLC()
    {
    CNfcEngine* self = new (ELeave) CNfcEngine();
    CleanupStack::PushL(self);
    self->ConstructL();
    return self;
    }

CNfcEngine* CNfcEngine::NewL()
    {
    CNfcEngine* self = CNfcEngine::NewLC();
    CleanupStack::Pop(); // self;
    return self;
    }

void CNfcEngine::ConstructL()
    {
    User::LeaveIfError(iFs.Connect());
    CREATE_LOG_INSTANCE(iFs, _L("E:\\NfcApiBridgeServerLog.txt"));
    
    iEnumCleanup.CreateL();
    iP2PManager = CP2PManager::NewL();
    
    LOG1(_L("Created CNfcEngine successfully"));
    }

void CNfcEngine::ReadTagAsyncL(scatu::MFunctor<HBufC8 *> & aRet, TDesC8 const & aWidgetId, TDesC8 const & aTnf, TDesC8 const & aType, TInt aTimeout)
    {
    LOG5(_L8("CNfcEngine::ReadTagAsyncL %S, %S, %S, %d"), &aWidgetId, &aTnf, &aType, aTimeout);
    ClientByIdL(aWidgetId)->ReadTagAsyncL(aRet, aTnf, aType, aTimeout);
    }

void CNfcEngine::SetForegroundL(TDesC8 const & aWidgetId, TBool aOnForeground)
    {
    LOG3(_L8("CNfcEngine::SetForegroundL %S, %d"), &aWidgetId, aOnForeground);
    ClientByIdL(aWidgetId)->SetForegroundL(aOnForeground);
    }

TInt CNfcEngine::SendMessageL(const TDesC8 & aWidgetId, const TDesC8 & aMessageId, const TDesC8 & aContent, TInt aValidFor)
	{
	LOG5(_L8("CNfcEngine::SendMessageL( \"%S\", \"%S\", \"%S\", %d )"), &aWidgetId, &aMessageId, &aContent, aValidFor );
	iP2PManager->SendMessageL(aWidgetId, aMessageId, aContent, aValidFor ); // TODO convert from valid for to valid until in here?
	return KErrNone;
	}

TInt CNfcEngine::SetResponseL(const TDesC8 & aWidgetId, const TDesC8 & aMessageId, const TDesC8 & aContent, TInt aValidFor)
	{
	LOG5(_L8("CNfcEngine::SetResponseL( \"%S\", \"%S\", \"%S\", %d )"), &aWidgetId, &aMessageId, &aContent, aValidFor );
	iP2PManager->SetResponseL(aWidgetId, aMessageId, aContent, aValidFor ); // TODO convert from valid for to valid until in here?
	return KErrNone;
	}

HBufC8 * CNfcEngine::TransactionLogL(const TDesC8 & aWidgetId)
	{
	LOG2(_L8("CNfcEngine::TransactionLogL( \"%S\" )"), &aWidgetId );
	return iP2PManager->TransactionLogL(aWidgetId);
	}

CNfcClient * CNfcEngine::ClientByIdL(TDesC8 const & aWidgetId)
    {
    CNfcClient * client = iClients.FindL(aWidgetId);
    if(!client)
        {
        client = CNfcClient::NewLC();
        iClients.InsertL(aWidgetId, client);
        CleanupStack::Pop(client);
        }
    return client;
    }
